package com.wlcorp.forcazamis.sys.permission;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultElement;

@SuppressWarnings("unchecked")
public class PermissionMap {
	private static PermissionMap paramMap;

	private String xmlFilePath;

	private Document paramDoc;

	private PermissionMap() {
	}

        @SuppressWarnings("unchecked")
		public List getPermissionGroups(){
          List resultList = new ArrayList();
               Element root = paramDoc.getRootElement();
               List permissionGroupList = root.elements(PermissionXMLBuilder.GROUP_PERMISSION);
               for(Iterator iterator = permissionGroupList.iterator(); iterator.hasNext(); ){
                 Element topEl = (Element)iterator.next();
                 PermissionGroup permissionGroup = new PermissionGroup();
                 permissionGroup.setId(topEl.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID));
                 permissionGroup.setTitle(topEl.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_TITLE));
                 permissionGroup.setImagePath(topEl.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_IMAGEPATH));
                 resultList.add(permissionGroup);
               }

               return resultList;

        }
	/**
	 * @method: getGroups
	 * @param :
	 * @return Map key存储group的ID，value存储title
	 * TODO 得到所有分组
	 */
	public List getPermissionPages(){
                List resultList = new ArrayList();
		Element root = paramDoc.getRootElement();
                List topGroupList = root.elements(PermissionXMLBuilder.GROUP_PERMISSION);
                for(Iterator iterator = topGroupList.iterator(); iterator.hasNext(); ){
                  Element topEl = (Element)iterator.next();
                  List groupList = topEl.elements(PermissionXMLBuilder.PAGE_PERMISSION);
                  Element el;
                  for (Iterator iter = groupList.iterator(); iter.hasNext(); ) {
                    el = (Element) iter.next();
                    PermissionPage permissionPage = new PermissionPage();
                    permissionPage.setId(el.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID));
                    permissionPage.setTitle(el.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_TITLE));
                    permissionPage.setAction(el.attributeValue(PermissionXMLBuilder.
                                                      PARAM_ATTRIBUTE_ACTION));
                    permissionPage.setMethod(el.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_METHOD));
                    resultList.add(permissionPage);
                  }
                }

		return resultList;
	}

    public List getPermissionPagesByTopGroup(String topGroupId){
            List resultList = new ArrayList();
            Element root = paramDoc.getRootElement();
            List topGroupList = root.elements(PermissionXMLBuilder.GROUP_PERMISSION);
            for(Iterator iterator = topGroupList.iterator(); iterator.hasNext(); ){
              Element topEl = (Element)iterator.next();
              if(topEl.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID).equals(topGroupId)){
                List permissionPageList = topEl.elements(PermissionXMLBuilder.PAGE_PERMISSION);
                Element el;
                for (Iterator iter = permissionPageList.iterator(); iter.hasNext(); ) {
                  el = (Element) iter.next();
                  PermissionPage permissionPage = new PermissionPage();
                  permissionPage.setId(el.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID));
                  permissionPage.setTitle(el.attributeValue(PermissionXMLBuilder.
                                                   PERMISSION_ATTRIBUTE_TITLE));
                  permissionPage.setAction(el.attributeValue(PermissionXMLBuilder.
                                                    PARAM_ATTRIBUTE_ACTION));
                  permissionPage.setMethod(el.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_METHOD));
                  resultList.add(permissionPage);
                }
                break;
              }
            }

            return resultList;
    }

	public PermissionSub getParam(String id) {

		Element element = paramDoc.elementByID(id);
		if(element == null){
			//或报错
			return null;
		}
		PermissionSub param = new PermissionSub();
		param.setParentId(element.getParent().attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID));
		param.setId(id);
		param.setTitle(element
				.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_TITLE));
		param.setType(element
				.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_TYPE));
		boolean isEnumerated = true;
		if(element
				.attributeValue(PermissionXMLBuilder.PARAM_ATTRIBUTE_IS_ENUMERATED).equals("no")){
					isEnumerated = false;
		}
		param.setEnumerated(isEnumerated);
		param.setDesc(element
				.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_DESC));
		List valueElemList = element.elements(PermissionXMLBuilder.PERMISSION_VALUE);
		Map valueMap = new HashMap();
		Element value;
		for (Iterator iterator = valueElemList.iterator(); iterator.hasNext();) {
			value = (Element) iterator.next();
			valueMap.put(value.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID),value.getText());
		}
		param.setValues(valueMap); // valueMap里对象类型为String
		return param;
	}

	public void addParam(String groupID, PermissionSub param) {
		//验证结点ID是否重复
		if(paramDoc.elementByID(param.getId()) != null){
			return;
		}
		//如果不是枚举，则不允许value多于1个
		if(!param.isEnumerated() && (param.getValues().size() > 1)){
			return;
		}
		Element group = paramDoc.elementByID(groupID);

		Element newNode = new DefaultElement(PermissionXMLBuilder.SUB_PERMISSION);

		newNode.addAttribute(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID, param.getId());
		newNode.addAttribute(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_TITLE, param
				.getTitle());
		newNode.addAttribute(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_TYPE, param
				.getType());
		String isEnumerated = "yes";
		if(param.isEnumerated() == false){
			isEnumerated = "no";
		}
		newNode.addAttribute(PermissionXMLBuilder.PARAM_ATTRIBUTE_IS_ENUMERATED,
				isEnumerated);
		newNode.addAttribute(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_DESC, param
				.getDesc());
		Map valueList = param.getValues();
		String value;
		Element valueEl;
		int index = 1;

		for (Iterator iterator = valueList.values().iterator(); iterator.hasNext(); index++) {
			value = (String) iterator.next();
			valueEl = new DefaultElement(PermissionXMLBuilder.PERMISSION_VALUE);
			valueEl.addAttribute(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID, param
					.getId()
					+ "-" + index);
			valueEl.setText(value);
			newNode.add(valueEl);
		}
		group.add(newNode);
	}

	public void removeParam(String id) {
		Element el = paramDoc.elementByID(id);
		if (el != null) {
			Element parent = el.getParent();
			parent.remove(el);
		}

	}

	public static PermissionMap getInstance(String docPath) {
		if (paramMap == null) {
			paramMap = new PermissionMap();
			// 初始化代码
			paramMap.xmlFilePath = PermissionMap.class.getResource(docPath).getPath();
			SAXReader reader = new SAXReader();
			try {
				paramMap.paramDoc = reader.read(paramMap.xmlFilePath);
			} catch (DocumentException e) {
				// 出错处理，待修改
				e.printStackTrace();
			}
			//paramMap.paramDoc.setXMLEncoding("UTF-8");
		}
		return paramMap;
	}

	public void saveToFile() {
		FileWriter out;
		try {
			out = new FileWriter(xmlFilePath);
			paramDoc.write(out);
			out.close();
		} catch (IOException e) {
			// 出错处理，待修改
			e.printStackTrace();
		}

	}

	public List getPermissionSubList(String permissionPageId) {
		Element group = paramDoc.elementByID(permissionPageId);
		Element el;
		PermissionSub param;
		List paramList = new ArrayList();
		for (Iterator iterator = group.elementIterator(); iterator.hasNext();) {
			el = (Element) iterator.next();
			param = new PermissionSub();
			param.setParentId(group.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID));
			param.setId(el.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID));
			param.setTitle(el.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_TITLE));
			param.setType(el.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_TYPE));
			boolean isEnumerated = true;
			if(el.attributeValue(PermissionXMLBuilder.PARAM_ATTRIBUTE_IS_ENUMERATED).equals("yes")){
				isEnumerated = true;
			} else{
				isEnumerated = false;
			}
			param.setEnumerated(isEnumerated);
			param.setDesc(el.attributeValue(
					PermissionXMLBuilder.PERMISSION_ATTRIBUTE_DESC));
			List valueElemList = el.elements(PermissionXMLBuilder.PERMISSION_VALUE);
			Map valueMap = new HashMap();
			Element value;
			for (Iterator iter = valueElemList.iterator(); iter.hasNext();) {
				value = (Element) iter.next();
				valueMap.put(value.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID),value.getText());
			}
			//System.out.println("value=" + el.getStringValue());
			param.setValues(valueMap); // valueList里对象类型为id和String类型值
			paramList.add(param);
		}
		return paramList;
	}

	public void updateValue(String id,String value){
		Element el = paramDoc.elementByID(id);
		el.setText(value);
	}

	public void addValue(String value,String parentID){
		Element el = paramDoc.elementByID(parentID);
		List valueList = el.elements(PermissionXMLBuilder.PERMISSION_VALUE);
		Element lastValue = (Element)valueList.get(valueList.size() - 1);
		String lastValueID = lastValue.attributeValue(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID);
		//String last = lastValueID.substring(lastValueID.lastIndexOf("-"));
		int lastIndex = Integer.parseInt(lastValueID.substring(lastValueID.lastIndexOf("-") + 1));
		String newValueID = parentID + "-" + (++lastIndex);

		Element newValueEl = new DefaultElement("value");
		newValueEl.addAttribute(PermissionXMLBuilder.PERMISSION_ATTRIBUTE_ID,newValueID);
		newValueEl.setText(value);
		el.add(newValueEl);
	}

	public void saveToDb() {

	}
}
